package app.controllers.customer;

import app.models.wx.WxTicket;
import app.models.member.Member;
import app.models.member.TicketOptRecord;
import com.github.sog.controller.AjaxMessage;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.controller.security.Securitys;
import com.github.sog.kit.date.DateProvider;
import com.jfinal.plugin.activerecord.Page;

import java.util.Date;

/**
 * <p>
 * .
 * </p>
 *
 * @author Jerry Ou
 * @version 1.0 2014-02-12 13:41
 * @since JDK 1.6
 */
public class TicketController extends BasicController {
    public void index() {
        render("index.ftl");
    }

    public void list() {
        Member member = getModel(Member.class, "member");
        WxTicket ticket = getModel(WxTicket.class, "ticket");
        String uploadTime = getPara("uploadTime");
        final DatatablesCriterias criterias = getCriterias();
        Page<WxTicket> ticketPage = WxTicket.dao.customerTickets(criterias, member, ticket, uploadTime);

        renderDataTables(ticketPage, criterias);
    }

    public void exchange() {
        try {
            long ticketId = getParaToLong("ticketId", 0l);
            long memberId = getParaToLong("memberId", 0l);
            String integralStr = getPara("integral", "0");
            double integral = Double.parseDouble(integralStr);
            String ticketNo = getPara("ticketNo");

            if (TicketOptRecord.dao.findByTicketNo(ticketNo) != null) {
                renderJson(AjaxMessage.failure("兑换失败，小票号输入重复"));
                return;
            }

            long loginId = Securitys.getLoginMember().getId();
            final Date currentDate = DateProvider.DEFAULT.getCurrentDate();

            WxTicket ticket = new WxTicket();
            ticket.set("id", ticketId);
            ticket.set("added", true);
            ticket.set("add_time", currentDate);
            ticket.set("ticket_no", ticketNo);
            ticket.set("integral", integral);
            ticket.set("operation", loginId);
            ticket.set("operation_time", currentDate);
            ticket.update();

            //记录小票积分流水操作
            TicketOptRecord record = new TicketOptRecord();
            record.custometWxRecord(memberId, loginId, integral, ticketNo, ticketId);

            renderJson(AjaxMessage.ok("兑换成功"));
        } catch (Exception e) {
            renderJson(AjaxMessage.error("兑换失败"));
        }
    }

    public void pricute() {
        long ticketId = getParaToLong(0, 0l);
        WxTicket wxTicket = WxTicket.dao.findById(ticketId);
        setAttr("wxTicket", wxTicket);
        render("pricute.ftl");
    }
}
